package com.mx.adapt.anytype

import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

/**
 * 单行显示的Adapt
 */
abstract class MXSingleLineAdapt : MXBaseTypeAdapt<Any>(arrayListOf()) {
    final override fun getSpanSize(): Int {
        return 1
    }

    override fun getItemCount(): Int {
        if (!isCurrentAdaptShow) return 0
        showWidthAdapt?.let {
            if (it.itemCount <= 0) return 0
        }
        showIfAdaptEmpty?.let {
            if (it.itemCount > 0) return 0
        }
        return 1
    }

    override fun getItem(position: Int): Any? {
        return Any()
    }

    override fun bindView(position: Int, binding: ViewBinding, record: Any) {
        bindView(binding)
    }

    abstract fun bindView(binding: ViewBinding)


    private var showWidthAdapt: MXBaseTypeAdapt<*>? = null
    private var showIfAdaptEmpty: MXBaseTypeAdapt<*>? = null

    protected var isCurrentAdaptShow = true
    fun setShow(show: Boolean) {
        isCurrentAdaptShow = show
    }

    /**
     * 当adapt的数量=0时，当前也会隐藏
     */
    fun showWithAdapt(adapt: MXBaseTypeAdapt<*>?) {
        showWidthAdapt = adapt
        adapt?.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onChanged() {
                this@MXSingleLineAdapt.notifyItemChanged(0)
            }
        })
    }

    /**
     * 当adapt的数量 > 0 时，当前会隐藏
     */
    fun showIfAdaptEmpty(adapt: MXBaseTypeAdapt<*>?) {
        showIfAdaptEmpty = adapt
        adapt?.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onChanged() {
                this@MXSingleLineAdapt.notifyItemChanged(0)
            }
        })
    }
}